// views/txtdetail/index.js
var time = require('../../utils/util');

var BASE_URL = getApp().globalData.BASE_URL
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    zhulipop: false, //助力通知框
    // huoquphone: false, //获取手机号通知框
    zijipop: false, //自己点自己
    id: null, //活动详情的id
    article: '', //文章
    showloading: true, //没出来画面之前出来加载
    flag: '', //判断活动是否已经过期
    show: '', //判断是否已经授权手机号
    pid: '',
    fukuandingdanid: '',
    iflogin: false //扫码进来是否登录
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    console.log(options, '活动详情页的初始数据')
    var _this = this
    if (options.jsonStr) {
      wx.login({
        success: res => {
          wx.request({
            url: `${BASE_URL}/ajax/login`,
            data: {
              code: res.code
            },
            method: "GET",
            success: res => {
              this.setData({
                zhulipop: true
              })
              // 获取到用户的 openid
              wx.setStorage({
                key: "openid",
                data: res.data.openid
              })
              wx.setStorage({
                key: "sessionkey",
                data: res.data.session_key
              })
            }
          });
        }
      });
      _this.setData({
        fukuandingdanid: options.jsonStr
      })
    }
    var userInfo = wx.getStorageSync('data')
    if (options.openid) {
      if (options.openid == userInfo.openId) {
        wx.showModal({
          title: '提示',
          content: '自己不能给自己助力哦',
          showCancel: false,
          success(res) {
            if (res.confirm) {}
          }
        })
        _this.setData({
          zijipop: true,
        })
      }
    }
    this.setData({
      id: options.id,
      // id: 11912,
    })

  },

  //关闭助力弹窗
  onClose() {
    wx.showToast({
      title: '你取消了授权,助力失败',
      icon: 'none',
      duration: 2000
    })
    this.setData({
      zhulipop: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var _this = this;
    wx.request({
      url: `${BASE_URL}/ajax/wenzhangxiangqing?id=${_this.data.id}`,
      method: "GET",
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) {
        if (res.data.huodong) {
          if (res.data.huodong.status == 0) {
            _this.setData({
              flag: false //原本是false
            })
          } else {
            _this.setData({
              flag: true
            })
          }
        } else {
          _this.setData({
            flag: false //原本是false
          })
        }
        res.data.time = time.formatTimeTwo(res.data.time, 'Y-M-D');
        console.log(res)
        res.data.info = JSON.parse(res.data.info)
        _this.setData({
          pid: res.data.info.huodong_id,
          article: res.data,
          showloading: false
        })
      }
    })
  },

  //右边已经授权过手机号
  gogopay: function () {
    var _this = this
    var userInfo = wx.getStorageSync('USER')
    var opid = wx.getStorageSync('openid')
    var unid = wx.getStorageSync('unionid')
    var phonenumber = wx.getStorageSync('phoneNumber')
    console.log('此时已经授权过了，直接去付款,走的是已经登录过',
      _this.data.pid,
      userInfo.id,
      userInfo.username,
      opid,
      userInfo.openid,
      unid,
      phonenumber,
      'xiaochengxv',
      unid,
      unid
    )
    wx.request({
      url: `${BASE_URL}/huodong/zhulipay`,
      method: "GET",
      data: {
        unionid: unid,
        pid: _this.data.pid,
        uid: userInfo.id,
        username: userInfo.username,
        xopenid: opid,
        openid:userInfo.openid,
        tel: phonenumber,
        type: 'xiaochengxv'
      },
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) { //是否支付
        console.log(res, '生成订单id的接口数据')
        // if (res.data.status == 2) {
        //   wx.navigateTo({
        //     url: `./paypage/third/index?id=${_this.data.id}`
        //   })
        // } else {
        //   wx.navigateTo({
        //     url: `./helppage/index?id=${res.data.id}&huodongid=${_this.data.id}`
        //   })
        // }

        wx.navigateTo({
          url: `./helppage/index?id=${res.data.id}&huodongid=${_this.data.id}`
        })
      }
    })
  },



  //左边已经授权手机号
  gopay: function () {
    var _this = this
    var userInfo = wx.getStorageSync('USER')
    var opid = wx.getStorageSync('openid')
    var unid = wx.getStorageSync('unionid')
    var phonenumber = wx.getStorageSync('phoneNumber')
    console.log('此时已经授权过了，直接去付款,走的是已经搜全手机号',
      _this.data.pid,
      userInfo.id,
      userInfo.username,
      opid,
      unid,
      phonenumber,
      'xiaochengxv'
    )
    wx.request({
      url: `${BASE_URL}/huodong/zhulipay`,
      method: "GET",
      data: {
        openid:userInfo.openid,
        pid: _this.data.pid,
        unionid: unid,
        uid: userInfo.id,
        username: userInfo.username,
        xopenid: opid,
        tel: phonenumber,
        type: 'xiaochengxv'
      },
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) { //是否支付
        console.log(res, '生成订单id的接口数据')
        if (res.data.status == 2) {
          wx.navigateTo({
            url: `./paypage/third/index?id=${res.data.id}`
          })
        } else {
          wx.navigateTo({
            url: `./paypage/index?id=${res.data.id}&huodongid=${_this.data.id}`
          })
        }
      }
    })
  },


  getcode: function () {
    wx.login({
      success: res => {
        wx.request({
          url: `${BASE_URL}/ajax/login`,
          data: {
            code: res.code
          },
          method: "GET",
          success: res => {
            // 获取到用户的 openid
            wx.setStorage({
              key: "openid",
              data: res.data.openid
            })
            wx.setStorage({
              key: "sessionkey",
              data: res.data.session_key
            })
            wx.setStorage({
              key: "unionid",
              data: res.data.unionid
            })
          }
        });
      }
    });
  },

  goguoqi: function () {
    wx.redirectTo({
      url: `/views/index/activity/index`
    })
  },
  ifphone: function () {
    var value = wx.getStorageSync('phoneNumber')
    if (value) {
      return false
    } else {
      return true
    }
  },
  iflogin: function () {
    var value = wx.getStorageSync('USER')
    if (value) {
      return false
    } else {
      return true
    }
  },
  //获取用户信息
  getUserProfile: function () {
    var _this = this
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        wx.setStorage({
          key: "data",
          data: res.userInfo,
        })
        var openId = wx.getStorageSync('openid')
        var unionId = wx.getStorageSync('unionid')
        console.log(openId, unionId)
        _this.login(res.userInfo.avatarUrl, res.userInfo.city, res.userInfo.country, res.userInfo.gender, res.userInfo.language, res.userInfo.nickName, openId, res.userInfo.province, unionId)
      },
      fail: (res) => {
        wx.showToast({
          title: '取消授权',
          icon: 'none',
        })
      }
    })
  },

  //获取手机号
  getPhoneNumber: function (e) {
    var _this = this;
    wx.checkSession({
      success: function () {
        wx.request({
          url: `${BASE_URL}/ajax/getUserPhone`, //自己的解密地址
          data: {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            sessionKey: wx.getStorageSync("sessionkey")
          },
          method: "post",
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res, e)
            if (e.detail.errMsg == "getPhoneNumber:ok") {
              wx.setStorage({
                key: "phoneNumber",
                data: res.data.phoneNumber
              })
              var opid = wx.getStorageSync('openid')
              var unid = wx.getStorageSync('unionid')
              var data = wx.getStorageSync('data')
            
              console.log('没有授权过手机号,获取手机号后登录留德diy然后生成订单跳转到付款页面',opid, unid, res.data.phoneNumber,data)
              if (data == '') {
                wx.request({
                  url: `${BASE_URL}/ajax/wechatinfo`, //仅为示例，并非真实的接口地址
                  data: {
                    avatarUrl: '',
                    city: '',
                    country: '',
                    gender: '',
                    language: '',
                    nickName: '',
                    openId: opid,
                    province: '',
                    unionId: unid,
                    phonenumber: res.data.phoneNumber
                  },
                  method: "POST",
                  header: {
                    'content-type': 'application/json' // 默认值
                  },
                  success(res) {
                    console.log(res, '授权手机号找到diy用户')
                    wx.setStorage({
                      key: "USER",
                      data: res.data
                    })
                    var phoneNumber = wx.getStorageSync('phoneNumber')
                    wx.request({
                      url: `${BASE_URL}/huodong/zhulipay`,
                      method: "GET",
                      data: {
                        pid: _this.data.pid,
                        uid: res.data.id,
                        username: res.data.username,
                        xopenid: opid,
                        unionid: unid,
                        tel: phoneNumber,
                        openid:res.data.openid,
                        type: 'xiaochengxv'
                      },
                      header: {
                        'Content-Type': 'application/json' //GET方式是这个
                      },
                      success(res) {
                        console.log(res)
                        if (res.data.status == 2) {
                          wx.navigateTo({
                            url: `./paypage/third/index?id=${res.data.id}`
                          })
                        } else {
                          wx.navigateTo({
                            url: `./paypage/index?id=${res.data.id}&huodongid=${_this.data.id}`
                          })
                        }
                      }
                    })
                  }
                })
              }else{
                wx.request({
                  url: `${BASE_URL}/ajax/wechatinfo`, //仅为示例，并非真实的接口地址
                  data: {
                    avatarUrl: data.avatarUrl,
                    city: data.avatarUrl,
                    country: data.country,
                    gender: data.gender,
                    language: data.language,
                    nickName: data.nickName,
                    openId: opid,
                    province: data.avatarUrl,
                    unionId: unid,
                    phonenumber: res.data.phoneNumber
                  },
                  method: "POST",
                  header: {
                    'content-type': 'application/json' // 默认值
                  },
                  success(res) {
                    console.log(res, '授权手机号找到diy用户')
                    wx.setStorage({
                      key: "USER",
                      data: res.data
                    })
                    var phoneNumber = wx.getStorageSync('phoneNumber')
                    wx.request({
                      url: `${BASE_URL}/huodong/zhulipay`,
                      method: "GET",
                      data: {
                        pid: _this.data.pid,
                        uid: res.data.id,
                        username: res.data.username,
                        xopenid: opid,
                        unionid: unid,
                        openid:res.data.openid,
                        tel: phoneNumber,
                        type: 'xiaochengxv'
                      },
                      header: {
                        'Content-Type': 'application/json' //GET方式是这个
                      },
                      success(res) {
                        console.log(res)
                        if (res.data.status == 2) {
                          wx.navigateTo({
                            url: `./paypage/third/index?id=${res.data.id}`
                          })
                        } else {
                          wx.navigateTo({
                            url: `./paypage/index?id=${res.data.id}&huodongid=${_this.data.id}`
                          })
                        }
                      }
                    })
                  }
                })
              }
            } else {
              wx.showToast({
                title: '授权后才能参与此活动',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },

  //留德diy登录
  login: function (avatarUrl, city, country, gender, language, nickName, openId, province, unionId) {
    var _this = this
    wx.request({
      url: `${BASE_URL}/ajax/wechatinfo`, //仅为示例，并非真实的接口地址
      data: {
        avatarUrl: avatarUrl,
        city: city,
        country: country,
        gender: gender,
        language: language,
        nickName: nickName,
        openId: openId,
        province: province,
        unionId: unionId,
      },
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data == '该账号未注册') {
          wx.showToast({
            title: '登录失败请重试',
            icon: 'error',
            duration: 2000
          })
        } else {
          wx.setStorage({
            key: "USER",
            data: res.data
          })
          var opid = wx.getStorageSync('openid')
          var unid = wx.getStorageSync('unionid')
          console.log('没授权过,获取手机号',
            _this.data.pid,
            res.data.id,
            res.data.username,
            opid,
            'xiaochengxv',
            '留德diy登录', _this.data.fukuandingdanid, res.data.id
          )
          wx.request({
            url: `${BASE_URL}/huodong/zhulipay`,
            method: "GET",
            data: {
              pid: _this.data.pid,
              uid: res.data.id,
              username: res.data.username,
              xopenid: opid,
              unionid: unid,
              openid:res.data.openid,
              tel: '',
              type: 'xiaochengxv'
            },
            header: {
              'Content-Type': 'application/json' //GET方式是这个
            },
            success(res) {
              console.log(res)
              // if (res.data.status == 2) {
              //   wx.navigateTo({
              //     url: `./paypage/third/index?id=${res.data.id}`
              //   })
              // } else {
              //   wx.navigateTo({
              //     url: `./helppage/index?id=${res.data.id}&huodongid=${_this.data.id}`
              //   })
              // }
              wx.navigateTo({
                url: `./helppage/index?id=${res.data.id}&huodongid=${_this.data.id}`
              })
            }
          })
        }
      }
    })
  },

  //客服绑定
  handleContact(e) {},


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this
    _this.getcode()
    console.log(this.ifphone(), !_this.iflogin())
    _this.setData({
      show: _this.ifphone(),
      iflogin: !_this.iflogin()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})